﻿<?php
	@require('./dbconnect.php');
	mysqli_autocommit($db, FALSE);
	header('Content-Type: application/json');
	
	if (isset($_GET['order'])) {
		$order_id = $_GET['order'];
		$resArr = array();
		
		// Check customer validity
		$customer = $_GET['customer'];
		$customer_sql = "SELECT * FROM `customers` WHERE `id` = $customer;";
		if ($result = mysqli_query($db, $customer_sql)) {
			if (mysqli_num_rows($result) > 0) {
				mysqli_free_result($result);
				
				// Check time validity
				$timeString = $_GET['time'];
				$time = DateTime::createFromFormat('H:i:s d/m/Y', $timeString);

				if ($time !== false) {
					$timeString = $time->format('Y-m-d H:i:s');
					$update_sql = "UPDATE `orders` SET `customer` = $customer, `time` = '$timeString' WHERE `id` = $order_id;";
					
					if ($result = mysqli_query($db, $update_sql)) {
						//mysqli_free_result($result);
						
						$delete_sql = "DELETE FROM `orders_details` WHERE `order` = $order_id;";
						
						$product = $_GET['product'];
						$quantity = $_GET['quantity'];
						$sale_off = $_GET['sale_off'];
						if ($result = mysqli_query($db, $delete_sql)) {
							//mysqli_free_result($result);
							
							$check = true;
							foreach ($product as $key => $val) {
								$insert_sql = "INSERT INTO `orders_details` (`order`, `product`, `quantity`, `sale_off`) VALUES ($order_id, $val, $quantity[$key], $sale_off[$key]);";
								
								if ($result = mysqli_query($db, $insert_sql)) {
								
								} else {
									$check = false;
									$str = mysqli_error($db);
									if (strpos($str, "BIGINT UNSIGNED") !== false) {
										$str = "Số lượng của mặt hàng [ID: $val] không đủ đáp ứng hóa đơn";
									}
									echo json_encode(array('status' => 'failed', 'message' => $str));
									break;
								}
							}
							
							if ($check) {
								mysqli_commit($db);
								echo json_encode(array('status' => 'success', 'message' => 'Cập nhật dữ liệu thành công'));
							}
							
						} else {
							echo json_encode(array('status' => 'failed', 'message' => mysqli_error($db)));
						}
						
					} else { // update query failed to execute
						echo json_encode(array('status' => 'failed', 'message' => mysqli_error($db)));
					}
					
				} else { // update failed: invalid time
					echo json_encode(array('status' => 'failed', 'message' => 'Thời gian không đúng định dạng hh:mm:ss dd/mm/yyyy'));
				}
				
			} else { // update failed: invalid customer
				echo json_encode(array('status' => 'failed', 'message' => 'Không tìm thấy dữ liệu khách hàng'));
			}
			
		} else { // failed to query
			echo json_encode(array('status' => 'failed', 'message' => mysqli_error($db)));
		}
		
		//echo json_encode(array('info' => $resArr));
	}
?>